package com.yealove.lunchparty.web;

import com.yealove.common.utils.Constants;
import com.yealove.common.utils.DictItem;
import com.yealove.common.utils.Utils;
import com.yealove.lunchparty.bean.*;
import com.yealove.lunchparty.service.LunchpartyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * User: yealove
 * Date: 8/18/14
 * Time: 10:23 PM
 * Created with IntelliJ IDEA.
 */
@Controller
@RequestMapping("lunchparty")
@SessionAttributes(Constants.USER)
public class LunchPartyController {

    private LunchpartyService lunchpartyService;
    private static Logger log = LoggerFactory.getLogger(LunchPartyController.class);
    private static Logger m_log = LoggerFactory.getLogger(Constants.LoggerConstant.M_LOG);

    /**
     * 初始化
     *
     * @param map
     * @return
     */
    @RequestMapping("init")
    public String page(PageBean pageBean, ModelMap map) {
//        if (pageBean == null) {
//            pageBean = new PageBean();
//        }
//        pageBean.setTotalCount(lunchpartyService.getTodayMenuCount());
//        map.put("page", pageBean);

        Shop shop = null;
        if (shop == null) {
            shop = lunchpartyService.qryDefaultShop();
        }
        List<Menu> menus = lunchpartyService.getTodayMenu(shop.getId());
        log.debug("lunchparty/init.aciton - page - result: {}", menus.size());
        map.put("menus", menus);

        Auth auth = lunchpartyService.getAuthByKey(Constants.CLOSED_TIPS);
        map.put(Constants.CLOSED_TIPS, auth);

        User u = (User) map.get(Constants.USER);
        if (u != null) {
            u = lunchpartyService.login(u);
            map.put(Constants.USER, u);
        }
        return "main";
    }

    /**
     * 登录
     *
     * @param user
     * @param map
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("login")
    @ResponseBody
    public User login(User user, ModelMap map) throws InterruptedException {
        log.debug("login - username:{}, password:{}", user.getUsername(), user.getPassword());
        User u = lunchpartyService.login(user);
        if (u != null) {
            log.debug("[{}]登录成功!", u.getName());
            map.put(Constants.USER, u);
        }
        return u;
    }

    /**
     * 注册
     *
     * @param user
     * @param map
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("reg")
    @ResponseBody
    public String reg(User user, ModelMap map) throws InterruptedException {
        log.debug("reg - username:{}, password:{}", user.getUsername(), user.getPassword());
        if (lunchpartyService.isReg(user)) {
            return "exist";
        }
        lunchpartyService.reg(user);
        User u = lunchpartyService.login(user);
        if (u != null) {
            log.debug("[{}]注册成功!", u.getUsername());
            map.put(Constants.USER, u);
        }
        return "user";
    }

    /**
     * 登录验证
     */
    @RequestMapping("isLogin")
    @ResponseBody
    public String isLogin(ModelMap map) {
        User u = (User) map.get(Constants.USER);
        if (u != null) {
            log.debug("[{}]已登录过了！", u.getName());
            return "success";
        }
        log.debug("验证是否已登录...");
        return null;
    }

    /**
     * 获取今日订单
     *
     * @return
     */
    @RequestMapping("todayOrder")
    @ResponseBody
    public List<Order> getOrder() {
        List<Order> orders = lunchpartyService.getTodayOrder();
        log.debug("getOrder - result: {}, {}", orders.size(), orders);
        return orders;
    }

    /**
     * 获取某用户的订单
     *
     * @return
     */
    @RequestMapping("showUserOrder")
    @ResponseBody
    public List<Order> getOrderByUid(String userId, ModelMap map) {
        User user = (User) map.get(Constants.USER);
        if (user == null || "0".equals(user.getIsAdmin()) || userId == null || "".equals(userId.trim())) {
            return new ArrayList<Order>(0);
        }
        DictItem dictItem = new DictItem();
        dictItem.setDictid(userId);
        dictItem.setDictname("7");

        List<Order> orders = lunchpartyService.getRecentOrder(dictItem);
        log.debug("showUserOrder - result: {}, {}", orders.size(), orders);
        return orders;
    }

    /**
     * 订餐
     *
     * @param order
     * @return
     */
    @RequestMapping("eatThis")
    @ResponseBody
    public String addOrder(Order order, ModelMap map) {
        User user = (User) map.get(Constants.USER);
        if (user != null) {
            m_log.info("-------------------- [{}] 订餐开始 --------------------", user.getName());
            order.setUserId(user.getId());
            log.debug("user {} add {}", user.getName(), order.getMenuId());
            order.setCreateDate(Utils.DateString(new Date()));
            m_log.info("订餐前金额：{}", user.getMoney());
            DictItem dictItem = new DictItem();
            dictItem.setDictid(user.getId());
            dictItem.setDictname(user.getMoney() - order.getPrice() + "");
            m_log.info("菜名：{}({})， 价格：{}", order.getMenuName(), order.getMemo(), order.getPrice());
            m_log.info("订餐后金额：{}", dictItem.getDictname());
            lunchpartyService.addOrder(order, dictItem);
            m_log.info("-------------------- [{}] 订餐结束 --------------------", user.getName());
            return Constants.SUCCESS;
        } else {
            return Constants.FAILED;
        }
    }

    /**
     * 统计
     *
     * @return
     */
    @RequestMapping("calc")
    @ResponseBody
    public List<DictItem> calc() {
        return lunchpartyService.calc();
    }

    /**
     * 获取用户余额
     *
     * @param map
     * @return
     */
    @RequestMapping("getMoney")
    @ResponseBody
    public String getMoney(ModelMap map) {
        User user = (User) map.get(Constants.USER);
        if (user != null) {
            User u = lunchpartyService.login(user);
            map.put(Constants.USER, u);
            return u.getMoney() + "";
        }
        return "0";
    }

    /**
     * 管理页面初始化
     *
     * @return
     */
    @RequestMapping("admin")
    public String adminInit(ModelMap map) {
        User user = (User) map.get(Constants.USER);
        if (user == null || "0".equals(user.getIsAdmin())) {
            return page(null, map);
        }
        List<User> users = lunchpartyService.getUsers();
        List<Auth> auths = lunchpartyService.getAuths();
        List<Shop> shops = lunchpartyService.getShops();
        map.put("users", users);
        map.put("auths", auths);
        map.put("shops", shops);
        return "admin";
    }

    /**
     * 充值
     *
     * @param dictItem
     * @return
     */
    @RequestMapping("pay")
    @ResponseBody
    public String pay(DictItem dictItem) {
        User user = lunchpartyService.getUserById(dictItem.getDictid());
        m_log.info("--------------------用户：[{}]， 金额变更开始--------------------", user.getName());
        Order order = new Order();
        order.setUserId(dictItem.getDictid());
        order.setCreateDate(Utils.DateString(new Date()));
        order.setMenuId("0");
        order.setMemo("before change, money is " + user.getMoney());
        order.setFlag(dictItem.getDictname());
        m_log.info("变更前金额：{}", user.getMoney());
        if ("".equals(dictItem.getDictname())) {
            m_log.info("金额调整...");
            dictItem.setDictname("0.0");
            log.info("{} pay money: {}", user.getName(), Math.abs(user.getMoney()));
        } else {
            m_log.info("金额变更量：{}", dictItem.getDictname());
            log.info("{} pay money: {}", user.getName(), dictItem.getDictname());
            dictItem.setDictname(Float.parseFloat(dictItem.getDictname()) + user.getMoney() + "");
        }
        m_log.info("变更前金额：{}", dictItem.getDictname());
        lunchpartyService.addOrder(order, dictItem);
        m_log.info("--------------------用户：[{}]， 金额变更结束--------------------", user.getName());
        return dictItem.getDictname();
    }

    /**
     * 个人信息
     *
     * @param map
     * @return
     */
    @RequestMapping("userInfo")
    public String userInfo(ModelMap map) {
        User user = (User) map.get(Constants.USER);
        if (user == null) {
            return page(null, map);
        }
        DictItem dictItem = new DictItem();
        dictItem.setDictid(user.getId());
        dictItem.setDictname("15");

        List<Order> orders = lunchpartyService.getRecentOrder(dictItem);
        Auth auth = lunchpartyService.getAuthByKey(Constants.TD_AUTH);
        map.put(Constants.TD_AUTH, auth);
        map.put("orders", orders);

        return "userInfo";
    }

    @RequestMapping("eatThat")
    @ResponseBody
    public String delOrder(String id, ModelMap map) {
        User user = (User) map.get(Constants.USER);
        m_log.info("-------------------- [{}] 退订开始 --------------------", user.getName());
        Order order = lunchpartyService.getOrderById(id);
        Auth auth = lunchpartyService.getAuthByKey(Constants.TD_AUTH);
        if (order == null) {
            m_log.info("-------------------- 退订异常... --------------------");
            m_log.info("-------------------- [{}] 退订结束 --------------------", user.getName());
            return Constants.FAILED;
        }
        if (auth.getStatus().equals("0")) {
            m_log.info("-------------------- 退订功能已关闭... --------------------");
            m_log.info("-------------------- [{}] 退订结束 --------------------", user.getName());
            return Constants.TD_AUTH_CLOSE;
        }
        DictItem dictItem = new DictItem();
        try {
            dictItem.setDictid(user.getId());
            dictItem.setDictname(order.getPrice() + user.getMoney() + "");
            m_log.info("[{}({})]退订[{}-{}-{}]", user.getName(), user.getUsername(), order.getMenuId(), order.getMenuName(), order.getPrice());
            m_log.info("退订前金额：{}", user.getMoney());
            m_log.info("退订后金额：{}", dictItem.getDictname());
            lunchpartyService.delOrderById(id, dictItem);
        } catch (Exception e) {
            m_log.info("-------------------- 退订异常... --------------------");
            m_log.info("-------------------- [{}] 退订结束 --------------------", user.getName());
            log.error("{}", e);
            return Constants.FAILED;
        }
        user.setMoney(Float.parseFloat(dictItem.getDictname()));
        map.put(Constants.USER, user);
        m_log.info("-------------------- [{}] 退订结束 --------------------", user.getName());
        return Constants.SUCCESS;
    }

    @RequestMapping("updateAuth")
    @ResponseBody
    public String updateAuth(DictItem dictItem, ModelMap map) {
        User user = (User) map.get(Constants.USER);
        String result = Constants.SUCCESS;
        if (user == null || "0".equals(user.getIsAdmin())) {
            result = Constants.FAILED;
        } else {
            try {
                lunchpartyService.updateAuth(dictItem);
            } catch (Exception e) {
                log.error("{}", e);
                result = Constants.FAILED;
            }
        }
        return result;
    }

    @RequestMapping("menuEdit")
    public String menuEdit(ModelMap map) {
        List<Shop> shops = lunchpartyService.getShops();
        map.put("shops", shops);
        return "menuEdit";
    }

    @RequestMapping("addShop")
    @ResponseBody
    public String addShop(Shop shop) {
        String result = Constants.SUCCESS;

        if (shop != null) {
            try {
                lunchpartyService.addShop(shop);
            } catch (Exception e) {
                result = Constants.FAILED;
                log.error("addShop error: {}", e);
            }
        }

        return result;
    }

    @RequestMapping("addMenu")
    @ResponseBody
    public String addMenu(Menu menu) {
        String result = Constants.SUCCESS;

        if (menu != null) {
            try {
                lunchpartyService.addMenu(menu);
            } catch (Exception e) {
                result = Constants.FAILED;
                log.error("addMenu error: {}", e);
            }
        }

        return result;
    }

    @RequestMapping("getShopMenus")
    @ResponseBody
    public List<Menu> getShopMenus(String id) {
        List<Menu> menus = new ArrayList<Menu>(0);
        if (id != null) {
            menus = lunchpartyService.getShopMenus(id);
        }
        return menus;
    }

    @RequestMapping("updateDefaultShop")
    @ResponseBody
    public String updateDefaultShop(String id) {

        String result = Constants.SUCCESS;

        try {
            lunchpartyService.updateDefaultShop(id);
        } catch (Exception e) {
            result = Constants.FAILED;
            log.error("updateDefaultShop error: {}", e);
        }

        return result;
    }

    @RequestMapping("delMenu")
    @ResponseBody
    public String delMenuById(String id) {

        String result = Constants.SUCCESS;

        try {
            lunchpartyService.delMenuById(id);
        } catch (Exception e) {
            result = Constants.FAILED;
            log.error("delMenu error: {}", e);
        }

        return result;
    }


    public void setLunchpartyService(LunchpartyService lunchpartyService) {
        this.lunchpartyService = lunchpartyService;
    }
}
